//
//  BDJianHuoHomeViewController.m
//  BeidouMall
//
//  Created by qie on 16/4/15.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "BDJianHuoHomeViewController.h"
#import "BDNavigationController.h"
#import "BDGoodDetailViewController.h"

#define kPageSize 5
#define firstHeightWidthRatio 1.8

@interface BDJianHuoHomeViewController () <UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray *_searchList;
    NSInteger _curPage;
    BOOL presentLoginView;
    NSString *_sortBy;
    NSString *_sortType;
    UIView *_jianhuoHeaderView;
    UIImageView *_navBarHairlineImageView;// 原生导航栏上的黑线,原来的自定义导航栏需要全透明所以原生的那条黑线需要隐藏，现在无所谓
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *topNumLabel;
@property (weak, nonatomic) IBOutlet UILabel *topPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *topScoreLabel;

@end

@implementation BDJianHuoHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 处理tableView上面多出来20个像素(是因为自动布局的缘故)
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    // 注册刷新头部和尾部
    [self setTableViewHeader];
    _tableView.mj_footer = [MJDIYBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadData:withHud:)];
    
    _searchList = [[NSMutableArray alloc] init];
    // 默认值
    _sortBy = @"SALE";
    _sortType = @"DESC";
    
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        self.topNumLabel.font = [UIFont fontWithName:@"Bzdbt" size:8.0];
        self.topPriceLabel.font = [UIFont fontWithName:@"Bzdbt" size:8.0];
        self.topScoreLabel.font = [UIFont fontWithName:@"Bzdbt" size:8.0];
    }
}

- (void)viewWillAppear:(BOOL)animated {// JianHuoHeaderView
    [super viewWillAppear:animated];
    
    [self hideNavgationBarBlackLine];
    // nav_bg2一个透明的图片替换原来的nav_bg
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bg2"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.translucent = YES;
    _jianhuoHeaderView = [[NSBundle mainBundle] loadNibNamed:@"JianHuoHeaderView" owner:nil options:nil].firstObject;
    _jianhuoHeaderView.frame = CGRectMake(0.0, 0.0, kScreen_Width, 64.0);
    _jianhuoHeaderView.tag = 957;
    [self.navigationController.view addSubview:_jianhuoHeaderView];
    [self dropShadowWithOffset:CGSizeMake(0, 0)
                        radius:2
                         color:[UIColor lightGrayColor]
                       opacity:0.8];
    
    
    if ([[BDAccountManagerModel shareInstance].payResult isEqualToString:@"selectTabBar"]) {// 当支付完成(成功或失败)跳回到根页面后要选择到我的这一项
        self.tabBarController.selectedIndex = 4;
    }
    
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        [self.navigationController.navigationBar
         setTitleTextAttributes:
         @{NSFontAttributeName:[UIFont fontWithName:@"BZDHT" size:12.0]}];
    } else {
        [self.navigationController.navigationBar
         setTitleTextAttributes:
         @{NSFontAttributeName:[UIFont boldSystemFontOfSize:18.0]}];
    }
    self.title = NSLocalizedString(@"jianhuo", nil);
    
    [_tableView.mj_header beginRefreshing];
}

- (void)dropShadowWithOffset:(CGSize)offset
                      radius:(CGFloat)radius
                       color:(UIColor *)color
                     opacity:(CGFloat)opacity {
    
    // Creating shadow path for better performance
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, self.navigationController.navigationBar.bounds);
    self.navigationController.navigationBar.layer.shadowPath = path;
    CGPathCloseSubpath(path);
    CGPathRelease(path);
    
    self.navigationController.navigationBar.layer.shadowColor = color.CGColor;
    self.navigationController.navigationBar.layer.shadowOffset = offset;
    self.navigationController.navigationBar.layer.shadowRadius = radius;
    self.navigationController.navigationBar.layer.shadowOpacity = opacity;
    
    // Default clipsToBounds is YES, will clip off the shadow, so we disable it.
    self.navigationController.navigationBar.clipsToBounds = NO;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _navBarHairlineImageView.hidden = NO;
    
    if (_jianhuoHeaderView) {
        [_jianhuoHeaderView removeFromSuperview];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark Private method

- (void)reloadData:(id) sender withHud:(BOOL) showHud {
    _curPage = sender == self ? 1 : _curPage + 1;
    if (_curPage == 1) {// 消除没有更多数据的状态
        [_tableView.mj_footer resetNoMoreData];
    }
    NSString *url;
    if ([[BDAccountManagerModel shareInstance].inBoundary isEqualToString:@"yes"]) {
        url = [NSString stringWithFormat:@"%@%@?currentPage=%ld&pageSize=%d&sortBy=%@&sortType=%@&hotType=BEST",
               [BDNetworking shareInstance].baseUrl,
               Good_Query,
               (long)_curPage,
               kPageSize,
               _sortBy,
               _sortType];
    } else {
        url = [NSString stringWithFormat:@"%@%@?currentPage=%ld&pageSize=%d&sortBy=%@&sortType=%@&hotType=BEST&excludeFirstLevels=%@",
               [BDNetworking shareInstance].baseUrl,
               Good_Query,
               (long)_curPage,
               kPageSize,
               _sortBy,
               _sortType,
               @"conveniency"];
    }
    
    MBProgressHUD *hud;
    if (showHud) {
//        hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view withText:@""];
    }
    
    [[BDNetworking shareInstance] postWithUrl:url sid:nil method:@"GET" parameters:nil completionHandler:^(NSObject *results, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([_tableView.mj_header isRefreshing]) {
                [_tableView.mj_header endRefreshing];
            }
            if ([_tableView.mj_footer isRefreshing]) {
                [_tableView.mj_footer endRefreshing];
            }
        });
        if (error != nil) {
            NSLog(@"尖货获取失败:%@",error);
            if (hud) {
                hud.labelText = NSLocalizedString(@"get top info Fail", nil);
                [hud hideAfterDelay:0.5];
            } else {
                [MBProgressHUD showToast:self.view withText:NSLocalizedString(@"get top info Fail", nil)];
            }
        } else {
            if (hud) {
                [hud hideAfterDelay:0.5];
            }
            if ([results isKindOfClass:[NSDictionary class]]) {
                NSLog(@"results = %@",results);
                NSDictionary *resultDic = (NSDictionary *)results;
                NSArray *resultList = resultDic[@"objects"];
                if ([resultList count] > 0) {
                    if ([resultList count] < kPageSize) {// 数据不够分页,显示没有更多了
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [_tableView.mj_footer endRefreshingWithNoMoreData];
                        });
                    }
                    if (sender == self) {
                        [_searchList removeAllObjects];
                    }
                    [_searchList addObjectsFromArray:resultList];
                } else {
                    if (_curPage > 1) { // 分页引起的刷新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [_tableView.mj_footer endRefreshingWithNoMoreData];
                        });
                    } else { // 刷新之前的数据应该清零
                        [_searchList removeAllObjects];
                    }
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [_tableView reloadData];
                });
            }
        }
    }];
}

- (void)setTableViewHeader {
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self reloadData:self withHud:NO];
    }];
    if ([[BDAccountManagerModel shareInstance].langage isEqualToString:@"zang"]) {
        header.stateLabel.font = [UIFont fontWithName:@"Bzdbt" size:9.0];
    }
    
    [header setTitle:NSLocalizedString(@"Pull down to refresh", nil) forState:MJRefreshStateIdle];
    [header setTitle:NSLocalizedString(@"Release to refresh", nil) forState:MJRefreshStatePulling];
    [header setTitle:NSLocalizedString(@"Loading ...", nil) forState:MJRefreshStateRefreshing];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    
    _tableView.mj_header = header;
}

- (void)hideNavgationBarBlackLine {
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
        NSArray *list=self.navigationController.navigationBar.subviews;
        for (id obj in list) {
            if ([obj isKindOfClass:[UIImageView class]]) {
                UIImageView *imageView=(UIImageView *)obj;
                NSArray *list2 = imageView.subviews;
                for (id obj2 in list2) {
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        UIImageView *imageView2=(UIImageView *)obj2;
                        _navBarHairlineImageView = imageView2;
                        _navBarHairlineImageView.hidden = YES;
                    }
                }
            }
        }
    }
}

#pragma mark tableView dataSrouce

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _searchList.count > 0 ? _searchList.count : 1 ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_searchList.count > 0) {
        static NSString *cellStr = @"searchCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        // 商店名称
        UILabel *storeNameLabel = (UILabel *)[cell viewWithTag:101];
        NSString *storeName = _searchList[indexPath.row][@"store"][@"name"];
        storeNameLabel.text = [NSString stringWithFormat:@"%@",storeName];
        // 商品图片
        NSString *goodImageUrl = _searchList[indexPath.row][@"icon"];
        UIImageView *goodImageView = (UIImageView *)[cell viewWithTag:102];
        if (![goodImageUrl isEqual:[NSNull null]]) {
            NSInteger width = goodImageView.width * 2;
            NSInteger height = goodImageView.height * 2;
            goodImageUrl = [NSString stringWithFormat:@"%@?dp_cmd=/imageView2/mode/2/w/%ld/h/%ld/",goodImageUrl,(long)width,(long)height];
            [goodImageView sd_setImageWithURL:[NSURL URLWithString:goodImageUrl] placeholderImage:[UIImage imageNamed:@"placeholder"]];
        }
        // 商品折扣价格
        UILabel *goodDiscountLabel = (UILabel *)[cell viewWithTag:103];
        NSString *goodDiscount = _searchList[indexPath.row][@"commodityPrice"][@"discount"];
        NSString *goodPrice = _searchList[indexPath.row][@"commodityPrice"][@"price"];
        if (![goodDiscount isEqual:[NSNull null]] &&
            ![goodPrice isEqual:[NSNull null]]) {
            // 折扣价格
            CGFloat discount = [goodDiscount floatValue];
            CGFloat price = [goodPrice floatValue];
            goodDiscountLabel.text = [NSString stringWithFormat:@"¥ %.2f",price * discount];
        }
        
        // 商品名称
        UILabel *goodNameLabel = (UILabel *)[cell viewWithTag:104];
        NSString *goodName = _searchList[indexPath.row][@"name"];
        if (![goodName isEqual:[NSNull null]]) {
            goodNameLabel.text = goodName;
        }
        
        return cell;
    } else {
        static NSString *cellStr = @"noCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        return cell;
    }
}

#pragma mark tableView delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return _searchList.count > 0 ? (kScreen_Width / firstHeightWidthRatio + 60.0) : kScreen_Height - 104.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_searchList.count > 0) {
        NSString *commodityId = _searchList[indexPath.row][@"commodityId"];
        if ([commodityId isEqual:[NSNull null]] ||
            commodityId != nil) {
            UIStoryboard *stroyboard = [UIStoryboard storyboardWithName:@"SecondStoryboard" bundle:[NSBundle mainBundle]];
            BDGoodDetailViewController *detailVC = [stroyboard instantiateViewControllerWithIdentifier:@"goodDetailStoryboardID"];
            detailVC.commodityId = commodityId;
            detailVC.isFromHomePage = YES;
//            detailVC.notCustomNavigatonBar = YES;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
